<template>
  <el-card class="box-card">
    <template #header>
      <el-tabs v-model="activeTab" @tab-click="handleTabChange">
        <el-tab-pane label="价格比对预警" name="价格比对" />
        <el-tab-pane label="合同合规预警" name="合同合规" />
        <el-tab-pane label="空置监测预警" name="空置" />
      </el-tabs>
    </template>
    <div class="asset-list-container">
      <el-table
        :data="tableData"
        style="width: 100%"
        height="calc(100% - 0px)"
        :header-cell-style="{
          background: '#F5F7FA',
          color: '#606266',
          fontWeight: 500,
        }"
        class="auto-scroll-table"
        ref="scroll_Table"
        @mouseenter="handleMouseEnter"
        @mouseleave="handleMouseLeave"
        v-loading="loading"
      >
        <el-table-column prop="project" label="资产名称" show-overflow-tooltip>
          <template #default="scope">
            <el-link
              type="primary"
              :underline="false"
              @click.stop="handleWarningClickByText(scope.row)"
              >{{ scope.row.project }}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column
          prop="assetCode"
          label="资产编号"
          show-overflow-tooltip
        />
        <el-table-column
          prop="managerName"
          label="资产负责人"
          show-overflow-tooltip
        />
        <el-table-column
          prop="createTime"
          label="预警日期"
          width="160"
          show-overflow-tooltip
        />
        <!-- <el-table-column prop="warningType" label="预警类型" width="180">
          <template #default="scope">
            <div class="warning-types">
              <template v-if="scope.row.warningType">
                <el-tag
                  v-for="(type, idx) in getWarningTypes(scope.row.warningType)"
                  :key="idx"
                  :type="getWarningTypeTag(type)"
                  size="small"
                  class="warning-tag"
                >
                  {{ type }}
                </el-tag>
              </template>
              <span v-else class="no-warning">无预警</span>
            </div>
          </template>
        </el-table-column> -->
      </el-table>
      <!-- 资产抽屉 -->
      <asset-drawer
        v-model:visible="drawerVisible"
        :type="drawerType"
        :asset-data="currentAssetData"
      />
    </div>
  </el-card>
</template>

<script setup>
import { computed, ref, onMounted, onUnmounted, watch, nextTick } from "vue";
import { getSpecAssetList } from "../../dashBoard/services";
import AssetDrawer from "@/views/assetList/components/AssetDrawer.vue";
import {
  getRentPriceComparison,
  getDocumentReviewInfoByAssetCode,
} from "@/views/assetList/services";

const props = defineProps({
  data: {
    type: Array,
    required: true,
    default: () => [],
  },
});

const warningTextMap = {
  空置: "vacancy",
  合同合规: "contract",
  价格比对: "price",
  价格比对: "price",
  无合同: "noContract",
};
const drawerType = ref("");
const currentAssetData = ref(null);
const drawerVisible = ref(false);

const scroll_Table = ref(null);
const scrolltimer = ref(null);
const loading = ref(false);

// tab相关
const activeTab = ref("价格比对");
const rawData = ref([]);

const fetchTabData = async (type) => {
  loading.value = true;
  const res = await getSpecAssetList(type);
  rawData.value = res?.rows || [];
  loading.value = false;
};

const tableData = computed(() => [...rawData.value, ...rawData.value]);

const handleTabChange = (tab) => {
  fetchTabData(tab.paneName);
};

const handleMouseEnter = () => {
  autoScroll(true);
};

const handleMouseLeave = () => {
  autoScroll(false);
};

function tryStartScroll(retry = 0) {
  const divData =
    scroll_Table.value?.bodyWrapper ||
    scroll_Table.value?.$el?.querySelector(".el-scrollbar__wrap");
  if (divData && divData.scrollHeight > divData.clientHeight) {
    autoScroll(false);
  } else if (retry < 20) {
    setTimeout(() => tryStartScroll(retry + 1), 200);
  }
}

const handleWarningClickByText = (row) => {
  openDrawer(warningTextMap[activeTab.value], row);
};

// 打开抽屉
const openDrawer = async (type, row) => {
  drawerType.value = type;

  // 根据不同类型准备不同的数据
  if (type === "price") {
    try {
      currentAssetData.value = await getRentPriceComparison(row.id);
    } catch (error) {
      console.error("Failed to fetch price comparison data:", error);
      // Handle error appropriately
    }
  } else if (type === "contract") {
    try {
      const contractData = await getDocumentReviewInfoByAssetCode(
        row.assetCode
      );

      currentAssetData.value = {
        contractData: contractData.data.results,
        baseInfo: {
          project: row.project,
          assetCode: row.assetCode,
          address: row.address,
          count: row.count,
        },
      };
    } catch (error) {
      currentAssetData.value = {
        baseInfo: {
          project: row.project,
          assetCode: row.assetCode,
          address: row.address,
          count: row.count,
        },
        data: {},
      };
      // 可选：提示用户接口异常
    }
  } else if (type === "vacancy") {
  }

  currentAssetData.value = {
    ...currentAssetData.value,
    baseInfo: {
      project: row.project,
      assetCode: row.assetCode,
      address: row.address,
      count: row.count,
    },
  };

  drawerVisible.value = true;
  console.log(" currentAssetData.value======", currentAssetData.value);
};

onMounted(() => {
  fetchTabData(activeTab.value);
  tryStartScroll();
});

watch(
  () => rawData.value,
  () => {
    tryStartScroll();
  }
);

onUnmounted(() => {
  window.clearInterval(scrolltimer.value);
});

const autoScroll = (stop) => {
  const divData =
    scroll_Table.value?.bodyWrapper ||
    scroll_Table.value?.$el?.querySelector(".el-scrollbar__wrap");
  if (!divData) {
    return;
  }
  if (stop) {
    window.clearInterval(scrolltimer.value);
  } else {
    if (divData.scrollHeight <= divData.clientHeight) return;
    window.clearInterval(scrolltimer.value);
    scrolltimer.value = window.setInterval(() => {
      divData.scrollTop += 1;
      if (divData.scrollTop >= divData.scrollHeight / 2) {
        divData.scrollTop = 0;
      }
    }, 30);
  }
};

// 预警类型标签
const getWarningTypeTag = (type) => {
  const typeMap = {
    租金比对预警: "info", // 蓝色
    合同合规预警: "success", // 绿色
    空置监测预警: "warning", // 橙色
    无合同: "danger", // 红色
    价格比对: "info",
    合同合规: "success",
    空置: "warning",
  };
  return typeMap[type] || "info";
};

const getWarningTypes = (warningType) => {
  if (!warningType) return [];
  return warningType.split(";").map((type) => type.trim());
};
</script>

<style lang="scss" scoped>
.box-card {
  height: 260px;
  border: none;
  :deep(.el-card__body) {
    height: calc(100% - 55px);
    padding: 10px 20px !important;
  }
  :deep(.el-card__header) {
    padding: 0 20px !important;
    border-bottom: 1px solid #ebeef5;
  }

  :deep(.el-tabs__header) {
    margin: 0 !important;
  }
}

.asset-list-container {
  height: 100%;
}

.card-header {
  font-weight: 500;
  font-size: 16px;
  color: #303133;
}

:deep(.el-table) {
  // 设置表格行的悬浮效果
  .el-table__row:hover {
    cursor: pointer;
    background-color: #f5f7fa !important;
  }

  // 调整标签的样式
  .el-tag {
    border-radius: 2px;
  }
}

.warning-types {
  display: flex;
  flex-wrap: wrap;
}

.warning-tag {
  margin-right: 5px;
  margin-bottom: 5px;
}

.warning-tag.info {
  background: #409eff !important; // 蓝色
  color: #fff !important;
  border: none;
}
.warning-tag.success {
  background: #67c23a !important; // 绿色
  color: #fff !important;
  border: none;
}
.warning-tag.warning {
  background: #e6a23c !important; // 橙色
  color: #fff !important;
  border: none;
}
.warning-tag.danger {
  background: #f56c6c !important; // 红色
  color: #fff !important;
  border: none;
}
.no-warning {
  color: #999;
  font-size: 13px;
}
</style>
